import cv2
import os
import gradio as gr
import oss2
from 图像处理 import get_quantity
import time
import matplotlib.pyplot as plt


# 现已关闭相关代码中 bucket 、AccessKey与 ai 的 apikey
# 需要演示的，可以下载 app.py 以及 图像处理.py，部署到本地，输入自己创建的即可
# （本案例使用阿里云 oss 对象存储，以及阿里云研发的大规模视觉语言模型的Qwen-VL）
access_key_id = "your_key_id"
access_key_secret = "your_key_secret"
endpoint="your_endpoint"
bucket_name="your_bucket_name"
# 阿里云OSS配置
auth = oss2.Auth(access_key_id, access_key_secret)
bucket = oss2.Bucket(auth, endpoint, bucket_name)


def upload_image_to_oss(local_image_path):
    """
    将本地图片上传到阿里云OSS并返回图片URL
    """
    object_name = os.path.basename(local_image_path)
    result = bucket.put_object_from_file(object_name, local_image_path)
    if result.status == 200:
        return f'https://{bucket_name}.{endpoint}/{object_name}'
    return None

def call_get_quantity_with_retry(image_url,description_word, max_retries=3):
    retries = 0
    while retries < max_retries:
        try:
            return get_quantity(image_url,description_word)
        except Exception as e:
            error_message = str(e)
            if "invalid_parameter_error" in error_message and "Failed to download multimodal content" in error_message:
                print("可能AI服务出现问题，检查服务是否到期或配置是否正确。")
            print(f"Error calling get_quantity: {e}. Retrying ({retries + 1}/{max_retries})...")
            retries += 1
            time.sleep(2)  # 等待2秒后重试
    return None

def process_video(video, description_word, time_interval):
    # 创建临时文件夹用于存储提取的图片
    temp_dir = "temp_frames"
    if not os.path.exists(temp_dir):
        os.makedirs(temp_dir)

    # 打开视频文件
    cap = cv2.VideoCapture(video)
    frame_rate = cap.get(cv2.CAP_PROP_FPS)
    frame_interval = int(frame_rate * time_interval)

    values = []  # 用于存储每个图片对应的value值

    frame_count = 0
    while True:
        ret, frame = cap.read()
        if not ret:
            break
        if frame_count % frame_interval == 0:
            # 保存当前帧为图片
            image_path = os.path.join(temp_dir, f"frame_{frame_count}.jpg")
            cv2.imwrite(image_path, frame)

            # 上传图片到OSS并获取URL
            image_url = upload_image_to_oss(image_path)
            if image_url:
                # 调用AI函数获取值
                #value = get_quantity(image_url, description_word)
                value = call_get_quantity_with_retry(image_url,description_word)
                if value is not None:
                    values.append(value)

            # 删除临时图片
            os.remove(image_path)
        frame_count += 1

    # 释放视频捕获对象
    cap.release()
    # 删除临时文件夹
    os.rmdir(temp_dir)

    # 设置支持中文的字体，这里使用黑体
    plt.rcParams['font.family'] = 'SimHei'
    # 解决负号显示为方块的问题
    plt.rcParams['axes.unicode_minus'] = False

    # 绘制折线图
    if values:
        plt.figure(figsize=(10, 6))
        plt.plot(range(len(values)), values, marker='o')
        plt.xlabel('图片序列')
        plt.ylabel('对应值')
        plt.title('根据描述词的评估值折线图')
        plt.grid(True)
        plot_path = "value_plot.png"
        plt.savefig(plot_path)
        plt.close()
        return plot_path
    return None


# 创建Gradio界面
iface = gr.Interface(
    fn=process_video,
    inputs=[
        gr.Video(label="上传视频"),
        gr.Textbox(label="描述词"),
        gr.Number(label="时间间隔（秒）", value=1.0)
    ],
    outputs=gr.Image(label="Value Plot"),
    title="视频处理与AI分析",
    description="上传视频，输入描述词和时间间隔，系统将分析视频并显示各帧值的折线图。"
)

# 启动界面
iface.launch()